package com.xywy.fwc;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.analytics.MobclickAgent;
import com.xywy.R;
import com.xywy.common.util.FileUtil;
import com.xywy.common.widget.MyProgress;
import com.xywy.fwc.adapter.FwcAsseaAdapter;
import com.xywy.fwc.adapter.FwcMenuListAdapter;
import com.xywy.fwc.bean.FwcAssea;
import com.xywy.fwc.bean.FwcHomeData;
import com.xywy.fwc.bean.FwcItem;
import com.xywy.fwc.net.AsseaParser;
import com.xywy.fwc.net.DataCallBack;
import com.xywy.fwc.net.MenuParser;
import com.xywy.fwc.net.Request;
import com.xywy.fwc.net.SignParser;
import com.xywy.me.bean.UserKeeper;

/**
 * 服务窗 点击进入
 * 
 * @author wangwenlong
 * 
 */
public class FwcMessageInfo extends Activity implements OnClickListener {
	private Button mBack;
	private TextView mTitle;
	private TextView mGo;

	private String userid;
	private String mSign; // 签名
	private SharedPreferences sp;
	private FwcHomeData mData;
	private static final String menuUrl = "http://api.yun.xywy.com//index.php/server/api/menu/menu_list/";
	private static final String infoUrl = "http://api.yun.xywy.com/index.php/server/api/service_provider/introduce/"; // 详情

	private static final String essaUrl = "http://api.yun.xywy.com/index.php/server/api/news_type/type_list/"; // 文章列表

	private List<FwcItem> menus;
	private List<FwcItem> subMenus;
	private LinearLayout mBottomLin;

	private static final int MENU_SUCCESS = 0;
	private static final int MENU_FAIL = 1;
	private static final int LIST_SUCCESS = 2;
	private static final int LIST_FAIL = 3;

	private static final int ESSA_TEXT = 1;
	private static final int ESSA_IMG = 2;
	private static final int ESSA_MOREIMG = 3;

	private List<List<FwcAssea>> mAsseaList;
	private FwcAsseaAdapter adapter;
	private ListView mFwcList;
	private PopupWindow menuWindow;
	private int width;
	private ImageView headIv;
	private MyProgress progress;
	
	private String mSignUrl = "http://api.yun.xywy.com/index.php/server/api/service_provider/create_sn//"; //获取签名

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.fwc_messageinfo);
		init();
		initView();
		loadData();
	}

	private void init() {
		sp = getSharedPreferences("config", Context.MODE_PRIVATE);
//		userid = sp.getString("userid", "");
		userid = UserKeeper.getCurrentUser(this).getUserid();
		mSign = sp.getString(userid + "sign", "");
		Intent intent = getIntent();
		mData = (FwcHomeData) intent.getSerializableExtra("data");
		WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
		width = wm.getDefaultDisplay().getWidth() / 3;
		progress = new MyProgress(this, 30000);
	}

	private void initView() {
		mBack = (Button) findViewById(R.id.bt_title_back);
		mTitle = (TextView) findViewById(R.id.tv_title);
		mTitle.setText(mData.getName());
		mBack.setOnClickListener(this);
		mBottomLin = (LinearLayout) findViewById(R.id.bottomLinear);
		mFwcList = (ListView) findViewById(R.id.fwcList);
		headIv = (ImageView) findViewById(R.id.headIv);
		headIv.setOnClickListener(this);
		findViewById(R.id.tv_title_back).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						finish();
					}
				});
	}

	private void loadData() {
		progress.start();
		
		long time = sp.getLong("signtime", -1);
		long currentTime = System.currentTimeMillis();
		if(time != -1){
			long diff = currentTime - time;
			if(diff/(1000*60*60)>4){
				getSign();
			}else {
				System.out.println(mSign+"-----");
				Request.requestData(new MenuParser(), callback, menuUrl + mData.getId()
						+ "/" + mSign+"/"+userid);
				// Request.requestData(new SignParser(), infoCall,
				// infoUrl+mData.getId()+"/"+mSign);
				Request.requestData(new AsseaParser(), infoCall,
						essaUrl + mData.getId() + "/" + mSign);
			}
		}else {
			getSign();
		}
	}

	DataCallBack<List<List<FwcAssea>>> infoCall = new DataCallBack<List<List<FwcAssea>>>() {

		@Override
		public void dataCall(List<List<FwcAssea>> t) {
			// TODO Auto-generated method stub
			mAsseaList = t;
			if (mAsseaList != null && mAsseaList.size() > 0) {
				responseHandler.sendEmptyMessage(LIST_SUCCESS);
				FileUtil.saveObject(userid + mData.getId()
						+ FileUtil.FWC_INNER_LIST, mAsseaList);
			} else {
				responseHandler.sendEmptyMessage(LIST_FAIL);
			}
		}
	};

	/**
	 * 处理底部栏
	 */
	DataCallBack<List<FwcItem>> callback = new DataCallBack<List<FwcItem>>() {

		@Override
		public void dataCall(List<FwcItem> t) {
			// TODO Auto-generated method stub
			menus = t;
			if (menus != null && menus.size() > 0) {
				FileUtil.saveObject(userid + mData.getId()
						+ FileUtil.FWC_BOTTOM_MENU, menus);
				responseHandler.sendEmptyMessage(MENU_SUCCESS);
			} else {
				responseHandler.sendEmptyMessage(MENU_FAIL);
			}
		}
	};
	Handler responseHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (progress != null)
				progress.stop();
			switch (msg.what) {
			case MENU_SUCCESS:
				if (menus != null)
					setBottom();
				break;
			case MENU_FAIL:
				Toast.makeText(FwcMessageInfo.this,
						getString(R.string.common_net_fail), 1).show();
				menus = (List<FwcItem>) FileUtil.getObject(userid
						+ mData.getId() + FileUtil.FWC_BOTTOM_MENU);
				if (menus != null)
					setBottom();
				break;
			case LIST_SUCCESS:
				if (mAsseaList != null) {
					adapter = new FwcAsseaAdapter(mAsseaList,
							FwcMessageInfo.this,mData.getName());
					mFwcList.setAdapter(adapter);
				}
				break;
			case LIST_FAIL:
				Toast.makeText(FwcMessageInfo.this,
						getString(R.string.common_net_fail), 1).show();
				mAsseaList = (List<List<FwcAssea>>) FileUtil.getObject(userid
						+ mData.getId() + FileUtil.FWC_INNER_LIST);
				if (mAsseaList != null) {
					adapter = new FwcAsseaAdapter(mAsseaList,
							FwcMessageInfo.this,mData.getName());
					mFwcList.setAdapter(adapter);
				}
				break;

			default:
				break;
			}
		};
	};

	private void setBottom() {
		LayoutInflater inflater = LayoutInflater.from(this);
		for (int i = 0; i < menus.size(); i++) {
			View view = inflater.inflate(R.layout.fwc_bottom_view, null);
			TextView tv = (TextView) view.findViewById(R.id.info);
			final FwcItem item = menus.get(i);
			tv.setText(item.getTitle());
			ImageView ivmenu = (ImageView) view.findViewById(R.id.menu);
			if (item.getFwcItem() != null && item.getFwcItem().size() > 0) {
				ivmenu.setVisibility(View.VISIBLE);
			} else {
				ivmenu.setVisibility(View.INVISIBLE);
			}
			LayoutParams params = new LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
			params.weight = 1;
			view.setTag(item);
			final int position = i;
			view.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					FwcItem item = (FwcItem) v.getTag();
					if (item.getFwcItem() != null
							&& item.getFwcItem().size() > 0) {
						// 弹窗
						initPop(item.getFwcItem(), position);
					} else {
						// 直接跳转
						Intent intent = new Intent(FwcMessageInfo.this,
								FwcWebView.class);
						intent.putExtra("item", item);
						Stattistics(item.getTitle(),item.getUrl());
						startActivity(intent);
					}
				}
			});
			mBottomLin.addView(view, params);
		}
	}

	private void initPop(final List<FwcItem> items, int position) {
		View view = View.inflate(this, R.layout.fwc_bottom_pop, null);
		menuWindow = new PopupWindow(view, LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);
		menuWindow.setBackgroundDrawable(new BitmapDrawable());
		menuWindow.setFocusable(true);
		menuWindow.setOutsideTouchable(true);
		menuWindow.setWidth(width + 40);
		ListView lv = (ListView) view.findViewById(R.id.menuList);
		lv.setAdapter(new FwcMenuListAdapter(items, this));
		switch (position) {
		case 0:
			menuWindow.showAtLocation(mBottomLin,
					Gravity.BOTTOM | Gravity.LEFT, dip2px(this, 10),
					 mBottomLin.getHeight());
			break;
		case 1:
			menuWindow.showAtLocation(mBottomLin, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, dip2px(this, 10),
					mBottomLin.getHeight());
			break;
		case 2:
			menuWindow.showAtLocation(mBottomLin, Gravity.BOTTOM
					| Gravity.RIGHT, dip2px(this, 10), mBottomLin.getHeight());
			break;

		default:
			break;
		}
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(FwcMessageInfo.this,
						FwcWebView.class);
				intent.putExtra("item", items.get(position));
				menuWindow.dismiss();
				menuWindow = null;
				startActivity(intent);
			}
		});
	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.bt_title_back:
			finish();
			break;
		case R.id.headIv:
			Intent intent = new Intent(this, FwcUserInfo.class);
			intent.putExtra("data", mData);
			startActivity(intent);
			break;
		default:
			break;
		}
	}
	
	/**
	 * 友盟统计收藏 帮助
	 */
	public void Stattistics(String title,String url){
		Map<String, String> params = new HashMap<String, String>();
			params.put("title",url); //代表来源
			MobclickAgent.onEvent(this, "Fwc_001", params);
	}
	
	/**
	 * 获取签名
	 */
	private void getSign(){
		Request.requestData(new SignParser(), singCall, mSignUrl+userid);
	}
	
	DataCallBack singCall = new DataCallBack<String>() {

		@Override
		public void dataCall(String t) {
			// TODO Auto-generated method stub
			if(t == null){
				responseHandler.sendEmptyMessage(LIST_FAIL);
				responseHandler.sendEmptyMessage(MENU_FAIL);
				return;
			}
			mSign = t;
			sp.edit().putLong("signtime", System.currentTimeMillis());
			sp.edit().putString(userid+"sign", mSign).commit();
			Request.requestData(new MenuParser(), callback, menuUrl + mData.getId()
					+ "/" + mSign+"/"+userid);
			// Request.requestData(new SignParser(), infoCall,
			// infoUrl+mData.getId()+"/"+mSign);
			Request.requestData(new AsseaParser(), infoCall,
					essaUrl + mData.getId() + "/" + mSign);
		}
	};
}
